package com.example.backend.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;


/**
 * @Author Jcy
 * @Date 2022/4/14
 */

public class JWTUtil {


    // 过期时间 5min
    private static final Long EXPIRE_TIME = 30 * 24 * 60 * 60 * 1000L;
    // 密钥
    private static final String SECRET = "SHIRO+JWT";

    // 生成token，5min后过期,token中含有userid的信息
    public static String createToken(int userid) {

        try {
            // 过期时间
            Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 加密算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withClaim("userid",String.valueOf(userid))
                    .withExpiresAt(expireDate)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }
    public static boolean verify(String token, String userid) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //在token中附带了userid信息
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userid", String.valueOf(userid))
                    .build();
            //验证 token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }
    // 获取token中的信息，无需secret解密也能获得
    public static String getUserid(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);

            Claim  UserId = jwt.getClaim("userid");
            System.out.println("jwt.getClaim is "+UserId);
            String UserId_1 = UserId.asString();
            System.out.println("UserId.asInt() is "+UserId_1);
            return UserId_1;

        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
